package com.aididi.controller;

import com.aididi.RedissonLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: zx.xu
 * @Description:    不基于注解方式锁操作
 */
@Slf4j
@RestController
public class LockController {

    @Autowired
    RedissonLock redissonLock;
    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("lock-decrease-stock")
    public String lockDecreaseStock() throws InterruptedException {
        redissonLock.lock("lock", 10L);
        try {
            int stock = Integer.parseInt((String) redisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                int realStock = stock - 1;
                redisTemplate.opsForValue().set("stock", realStock + "");
                System.out.println("扣减成功，剩余库存:" + realStock);
                Thread.sleep(50);
                log.info("===lock===减完库存后,当前库存===" + realStock);
            }
        }finally {
            //如果该线程还持有该锁，那么释放该锁。如果该线程不持有该锁，说明该线程的锁已到过期时间，自动释放锁
            if (redissonLock.isHeldByCurrentThread("lock")) {
                redissonLock.unlock("lock");
            }
        }

        return "=================================";
    }

    @GetMapping("trylock-decrease-stock")
    public String trylockDecreaseStock() throws InterruptedException {
        try {
            //尝试加锁，做多等待5秒，上锁以后20秒自动解锁
            if (redissonLock.tryLock("trylock", 5L, 200L)) {
                int stock = Integer.parseInt((String) redisTemplate.opsForValue().get("stock"));
                if (stock > 0) {
                    int realStock = stock - 1;
                    redisTemplate.opsForValue().set("stock", realStock + "");
                    System.out.println("扣减成功，剩余库存:" + realStock);
                    Thread.sleep(50);

                    log.info("====tryLock===减完库存后,当前库存===" + realStock);
                }
            } else {
                log.info("[ExecutorRedisson]获取锁失败");
            }
        }catch (Exception e){
            log.error("错误 :{}",e);
        }finally {
            redissonLock.unlock("trylock");
        }

        return "===================================";
    }

}
